package com.hldsmart.smartda.activity.home;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.hldsmart.smartda.R;
import com.hldsmart.smartda.adapter.home.CommentAdapter;
import com.hldsmart.smartda.adapter.home.CommentReplyAdapter;
import com.hldsmart.smartda.base.BaseActivity;
import com.hldsmart.smartda.model.entity.Comment;
import com.hldsmart.smartda.model.entity.Reply;

import java.util.ArrayList;
import java.util.List;


public class IndividuActivity extends BaseActivity implements View.OnClickListener{
    private List<Comment> commentList;
    private CommentAdapter commentAdapter;
    private CommentReplyAdapter commentReplyAdapter;
    private ListView lv_user_comments;
    private static final int ONE_COMMENT_CODE = -1;
    private EditText edt_reply;
    private TextView more;
    private ImageView btn_comment, iv_individu_back;
    private Button btn_reply;
    private List<Reply> replyList;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    public static void startIndividuActivity(Context context) {
        Intent intent = new Intent(context, IndividuActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_individu);
        initView();
        initCommentData();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initView() {
        lv_user_comments = (ListView) this.findViewById(R.id.lv_comments);
        btn_comment = (ImageView) this.findViewById(R.id.iv_character_photos);
        more = (TextView) this.findViewById(R.id.tv_character_more);
        iv_individu_back = (ImageView) this.findViewById(R.id.iv_individu_back);
        commentList = new ArrayList<Comment>();

        more.setOnClickListener(this);
        iv_individu_back.setOnClickListener(this);
        btn_comment.setOnClickListener(addCommentListener);
    }

    /**
     * 初始化数据
     */
    private void initCommentData() {
        Comment comment = new Comment();
        comment.setUsername("鑫鑫");
        comment.setTime("提问于23分钟前");
        comment.setContent("我的儿子今天过生日，我想今天在巫山烤鱼店给他一个惊喜！");
        commentList.add(comment);

        Comment comment2 = new Comment();
        comment2.setUsername("虓爷");
        comment2.setTime("提问于53分钟前");
        comment2.setContent("我是二楼，今天想吃肉");
        commentList.add(comment2);

        commentReplyAdapter = null;
        commentAdapter = new CommentAdapter(this, commentList,
                replyToCommentListener, commentReplyAdapter,
                replyToReplyListener);
        lv_user_comments.setAdapter(commentAdapter);
    }

    /**
     * 发表评论的监听
     */
    private View.OnClickListener addCommentListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onCreateDialog(ONE_COMMENT_CODE, ONE_COMMENT_CODE);
        }
    };

    /**
     * 回复评论的监听（回复楼主）
     */
    private View.OnClickListener replyToCommentListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            onCreateDialog(ONE_COMMENT_CODE, position);
        }
    };

    /**
     * 互相回复的监听（楼中楼）
     */
    private View.OnClickListener replyToReplyListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int parentPosition = (Integer) v.getTag(R.id.tag_first);
            int childPosition = (Integer) v.getTag(R.id.tag_second);
            onCreateDialog(parentPosition, childPosition);
        }
    };

    /**
     * 弹出评论的对话框
     * @param parentPositon 父节点的position
     * @param childPostion  子节点的position
     * @return
     */
    protected Dialog onCreateDialog(final int parentPositon,
                                    final int childPostion) {
        final Dialog customDialog = new Dialog(this);
        LayoutInflater inflater = getLayoutInflater();
        View mView = inflater.inflate(R.layout.dialog_comment, null);
        edt_reply = (EditText) mView.findViewById(R.id.edt_comments);
        btn_reply = (Button) mView.findViewById(R.id.btn_send);

        customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        customDialog.setContentView(mView);
        customDialog.show();

        btn_reply.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (childPostion) {
                    case ONE_COMMENT_CODE:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(IndividuActivity.this, "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Comment comment = new Comment();
                            comment.setUsername("海盗");
                            comment.setContent(edt_reply.getText().toString());

                            commentList.add(comment);
                            commentAdapter.clearList();
                            commentAdapter.updateList(commentList);
                            commentAdapter.notifyDataSetChanged();
                            customDialog.dismiss();
                            edt_reply.setText("");
                        }
                        break;
                    default:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(IndividuActivity.this, "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Reply reply = new Reply();
                            reply.setUsername("虓" + parentPositon + childPostion);
                            reply.setContent(edt_reply.getText().toString());

                            if (parentPositon != -1) {
                                reply.setReplyTo(commentList.get(parentPositon)
                                        .getReplyList().get(childPostion)
                                        .getUsername());
                                commentList.get(parentPositon).getReplyList()
                                        .add(reply);
                            } else {
                                replyList = commentList.get(childPostion)
                                        .getReplyList();
                                replyList.add(reply);
                                commentList.get(childPostion).setReplyList(
                                        replyList);
                            }

                            commentAdapter.clearList();
                            commentAdapter.updateList(commentList);
                            commentAdapter.notifyDataSetChanged();
                            customDialog.dismiss();
                            edt_reply.setText("");
                        }
                        break;
                }
            }
        });
        return customDialog;
    }


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Individu Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_character_more:
                MorenewsActivity.startMorenewsActivity(this);
            break;
            case R.id.iv_individu_back:
                finish();
            break;
        }
    }
}
